import 'dart:convert';
import 'dart:core';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/ChatMsg.dart';
import 'package:flutter_chip/bean/Goods.dart';
import 'package:flutter_chip/bean/Order.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/GlobalEvent.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/database/db_goods.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/view_loading.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:provide/provide.dart';

class ChatPage extends StatefulWidget {
  final User user;
  final String msgTag;

  const ChatPage({Key key, this.user, this.msgTag}) : super(key: key);

  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  EasyRefreshController controller = EasyRefreshController();
  TextEditingController _textEditingScroller = TextEditingController();

  var _eventBusOn;

  // 滚动控制器
  ScrollController _scrollController;
  var _item = [];

  //Goods
  Goods _goods;

  //MyUser
  User myUser;

  bool loading = false;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _getGoods();
    _getMsgList(true);
    _onMsgEvent();
  }

  @override
  void dispose() {
    super.dispose();
    _textEditingScroller.dispose();
    _scrollController.dispose();
    controller.dispose();
    _eventBusOn.cancel();
  }

  @override
  Widget build(BuildContext context) {
    myUser = Provide.value<User>(context);
    return Scaffold(
      backgroundColor: Color(0XFFF2F0F3),
      appBar: AppBar(
        elevation: 0.0,
        backgroundColor: Colors.white,
        titleSpacing: 0,
        title: Text(
          widget.user.userName,
          style: TextStyle(fontSize: 16),
        ),
      ),
      body: ProgressDialog(
        msg: "订单创建中...",
        loading: loading,
        child: Column(
          children: <Widget>[
            _goodsWidget(),
            Expanded(child: _pageListWidget()),
            _sendWidget()
          ],
        ),
      ),
    );
  }

  ///商品简介
  Widget _goodsWidget() {
    String picUrl;
    if (null != _goods && null != _goods.goodsImg) {
      picUrl = _goods.goodsImg.split(",").first;
    }

    //图片展示
    Widget _picWidget = Container(
      width: 46,
      height: 46,
      child: CachedNetworkImage(
        imageUrl: Api.getUrl(picUrl),
        fit: BoxFit.cover,
        errorWidget: (context, url, error) => CommWidget.imgError(textSize: 10),
      ),
    );

    //价格展示
    String price = null != _goods ? "${_goods.price}" : "0.0";
    Widget _descWidget = Container(
      margin: EdgeInsets.only(left: 56),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text("￥:$price"),
          Text(
            "交易前聊一聊",
            style: TextStyle(color: Colors.grey, fontSize: 12),
          ),
        ],
      ),
    );

    //立即购买按钮
    Widget _btnWidget = GestureDetector(
      child: Offstage(
        child: Container(
          width: 60,
          height: 30,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: Colors.deepOrange,
            borderRadius: BorderRadius.circular(4),
          ),
          child: Text(
            "立即购买",
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w400,
              color: Colors.white,
            ),
          ),
        ),
        offstage: null != _goods && _goods.userId == myUser.userId,
      ),
      onTap: () {
        _createOrder();
      },
    );
    return Offstage(
      offstage: null == _goods,
      child: Container(
        height: 60,
        padding: EdgeInsets.all(10),
        color: Colors.white,
        child: Stack(
          children: <Widget>[
            Align(alignment: Alignment.centerLeft, child: _picWidget),
            Align(alignment: Alignment.centerLeft, child: _descWidget),
            Align(alignment: Alignment.centerRight, child: _btnWidget),
          ],
        ),
      ),
    );
  }

  ///聊天内容列表
  Widget _pageListWidget() {
    return EasyRefresh.custom(
      reverse: true,
      enableControlFinishRefresh: true,
      header: CommWidget.commHeader(),
      footer: CommWidget.commFooter(),
      controller: controller,
      scrollController: _scrollController,
      slivers: <Widget>[
        SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
          return _itemWidget(context, index);
        }, childCount: _item.length))
      ],
      onRefresh: () => _getMsgList(true),
      onLoad: () => _getMsgList(false),
    );
  }

  ///发送消息框框
  Widget _sendWidget() {
    //发送按钮
    Widget _sendWidget = GestureDetector(
      child: Container(
        width: 48,
        height: 32,
        alignment: Alignment.center,
        child: Text(
          "发送",
          style: TextStyle(color: Colors.white),
        ),
        decoration: BoxDecoration(
            color: Theme.of(context).accentColor,
            borderRadius: BorderRadius.circular(4)),
      ),
      onTap: () {
        if (_textEditingScroller.text.isEmpty) {
          Toast.show("不能发送空白信息");
          return;
        }
        _sendTo();
      },
    );
    //输入框
    Widget _textWidget = TextField(
      controller: _textEditingScroller,
      decoration: InputDecoration(
          contentPadding: EdgeInsets.all(2),
          border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4),
              borderSide: BorderSide.none),
          fillColor: Colors.white,
          filled: true),
      maxLines: null,
    );
    return Container(
      constraints: BoxConstraints(maxHeight: 144, minHeight: 56),
      color: Color(0XFFF7F7F7),
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(child: _textWidget),
          SizedBox(width: 10),
          _sendWidget
        ],
      ),
    );
  }

  Widget _itemWidget(BuildContext context, int index) {
    ChatMsg chatMsg = _item[index];
    Widget _headWidget = GestureDetector(
      onTap: () {
        if (chatMsg.fromId == widget.user.userId) {
          Routers.router.navigateTo(
              context, "${Routers.PAGE_USERINFO}?userId=${chatMsg.fromId}",
              transition: TransitionType.inFromRight);
        }
      },
      child: Container(
        width: 32,
        height: 32,
        margin: EdgeInsets.all(10),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(6),
          child: CachedNetworkImage(
            imageUrl: Api.getUrl(chatMsg.fromImage),
            fit: BoxFit.cover,
            errorWidget: (context, url, error) =>
                Image.asset(Comm.IMG_DEFAULT, fit: BoxFit.cover),
          ),
        ),
      ),
    );
    Color bgColor = Color(0xff9EEA6A);
    if (chatMsg.fromId == widget.user.userId) {
      bgColor = Colors.white;
    }

    Widget _contentWidget = Container(
      margin: EdgeInsets.only(top: 10),
      child: Text(chatMsg.message),
      padding: EdgeInsets.all(5),
      constraints: BoxConstraints(maxWidth: Comm.screenWidth - 102),
      decoration: BoxDecoration(
          color: bgColor,
          borderRadius: BorderRadius.circular(6),
          boxShadow: [BoxShadow(color: bgColor, blurRadius: 5)]),
    );

    MainAxisAlignment alignment = MainAxisAlignment.end;
    List<Widget> list = [_contentWidget, _headWidget];
    if (chatMsg.fromId == widget.user.userId) {
      alignment = MainAxisAlignment.start;
      list.clear();
      list = [_headWidget, _contentWidget];
    }

    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: alignment,
      children: list,
    );
  }

  ///发送消息
  Future _sendTo() async {
    Map<String, String> params = Map();
    params["sendTo"] = widget.user.userId;
    params["message"] = _textEditingScroller.text;
    params["msgType"] = "01";
    if (null != _goods) {
      params["msgTag"] = _goods.goodsId;
    }
    ChatMsg msgChat = ChatMsg(
        sendTo: widget.user.userId,
        message: _textEditingScroller.text,
        msgType: "01",
        fromId: myUser.userId,
        fromName: myUser.userName,
        fromImage: myUser.imgUrl);
    setState(() {
      _item.insert(0, msgChat);
    });
    Http.post(Api.URL_CHAT_SENDTO, params: params, successCallBack: (data) {
      _textEditingScroller.text = "";
    });
  }

  ///获取离线数据
  Future _getMsgList(bool isRefresh) async {
    if (isRefresh) {
      controller.resetLoadState();
    }

    Map<String, String> params = Map();
    params["fromId"] = widget.user.userId;
    if (!isRefresh && _item.length > 0) {
      ChatMsg chatMsg = _item.last;
      params["createAt"] = "${chatMsg.createAt}";
    }

    Http.get(Api.URL_CHAT_OFFLINE, params: params, successCallBack: (data) {
      List list = json.decode(data).map((m) => ChatMsg.fromJson(m)).toList();
      setState(() {
        if (isRefresh) {
          _item.clear();
          controller.finishRefresh();
        } else {
          controller.finishLoad(noMore: null == list || list.length < 10);
        }
        _item.addAll(list);
      });
      _setReadMsg();
    });
  }

  ///通知服务器，该条消息已读
  void _setReadMsg() async {
    String unReadId = "";
    _item.forEach((value) {
      ChatMsg chatMsg = value;
      if (chatMsg.status != 3) {
        unReadId += "${chatMsg.id},";
      }
      if (null == chatMsg.createAt) {
        _item.remove(value);
      }
    });
    if ("" != unReadId) {
      Http.get("${Api.URL_CHAT_READ}?ids=$unReadId");
    }
  }

  ///获取商品详情
  void _getGoods() async {
    if (null == widget.msgTag) {
      return;
    }
    String url = "${Api.URL_GOODSINFO}?goodsId=${widget.msgTag}";
    DBGoods _dbGoods = DBGoods();
    Set<String> list = await _dbGoods.queryAll();
    if (!list.contains(widget.msgTag)) {
      url += "&wantNum=1";
      _dbGoods.insert(widget.msgTag);
    }
    Http.get(url, successCallBack: (data) {
      setState(() {
        _goods = Goods.fromJson(json.decode(data));
      });
    });
  }

  ///数据回调监听
  void _onMsgEvent() {
    _eventBusOn = GlobalEvent().eventBus.on<ChatMsg>().listen((event) {
      print("view_chat===收到eventBus数据：${event.toJson()}");
      if (event.fromId == widget.user.userId) {
        Http.get("${Api.URL_CHAT_READ}?ids=${event.id}");
        setState(() {
          _item.insert(0, event);
        });
      }
    });
  }

  ///创建订单
  void _createOrder() async {
    setState(() {
      loading = true;
    });
    Map<String, String> params = Map();
    params["goodsId"] = _goods.goodsId;
    params["goodsName"] = _goods.goodsName;
    params["goodsInfo"] = _goods.goodsInfo;
    Http.post(Api.URL_ORDER_ADD, params: params, successCallBack: (data) {
      setState(() {
        loading = false;
      });
      Order order = Order.fromJson(json.decode(data));
      String path = "${Routers.PAGE_ORDERINFO}?orderId=${order.orderId}";
      Routers.router
          .navigateTo(context, path, transition: TransitionType.inFromRight);
    }, errorCallBack: (errorMsg) {
      setState(() {
        loading = false;
      });
      Toast.show(errorMsg);
    });
  }
}
